package com.juneyaoair.controller;

import com.juneyaoair.feign.TestFeign;
import com.netflix.hystrix.contrib.javanica.annotation.HystrixCommand;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.client.RestTemplate;

import java.util.HashMap;
import java.util.Map;

/**
 * @author 袁闻锴
 * @date 2020/10/31 10:47
 */
@RestController
public class GetTestController {

    @Autowired
    private RestTemplate restTemplate;
    @Autowired
    private TestFeign testFeign;

    @RequestMapping("getTest")
    public String getTest() {
        /*
         * ResponseEntity 响应体 封装的有响应的状态码 和 响应信息 以及响应体
         *
         * 将同一个应用（第二次启动时修改下controller返回内容）同时启动多个，调两次同一个接口，返回内容会不一样，说明发生轮询
         */
        ResponseEntity<String> entity = restTemplate.getForEntity("http://client-1/test?name=zhangsan", String.class);
        String object = restTemplate.getForObject("http://client-1/test?name=zhangsan", String.class);
        System.out.println(object);
        String body = entity.getBody();
        System.out.println("body" + body);
        HttpStatus statusCode = entity.getStatusCode();
        System.out.println("statusCode" + statusCode);
        return body;
    }

    @PostMapping("getTestPost")
    public String getTestPost() {

        Map<String, String> map = new HashMap<>();
        map.put("name", "渣渣辉");
        String result = restTemplate.postForObject("http://client-1/testPost", map, String.class);
        System.out.println("result = " + result);

        ResponseEntity<String> entity = restTemplate.postForEntity("http://client-1/testPost", map, String.class);
        System.out.println("entity = " + entity);
        System.out.println("entity.getBody() = " + entity.getBody());
        System.out.println("entity.getHeaders() = " + entity.getHeaders());

        return "ok";

    }

    //測試Feign
    @GetMapping("getTestFeign")
    public String getTestFeign() {
        return testFeign.getTestFeign("測試Feign");
    }

    //容错处理Hystrix
    @GetMapping("testHystrix")
    @HystrixCommand(fallbackMethod = "forHystrix")
    public String getTestHystrix(String s) {
        return testFeign.getTestFeign("一切正常");
    }

    public String forHystrix(String s) {
        return "服务出错，请稍候再试！";
    }

    //Feign集成Hystrix自带容错处理
    @GetMapping("testFeignHystrix")
    public String getTestFeignHyxtrix() {
        return testFeign.getTestFeign("一切ok！！！");
    }
}
